package com.um.jdy.common.member.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.StrUtil;
import com.um.jdy.common.member.code.LoginCode;
import com.um.jdy.common.member.constants.VerificationCodeConstant;
import com.um.jdy.common.member.service.ImageCodeService;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 邓南辉
 * 日期 2023/2/4
 * 版权所有 广州优匠科技有限公司
 */
@Service
@Slf4j
public class ImageCodeServiceImpl implements ImageCodeService {

    @Autowired
    CacheService cacheService;

    @Autowired
    HttpServletResponse response;

    /**
     * 获取图形验证码文件流
     */
    public void get() {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(180, 80);
        RandomGenerator randomGenerator = new RandomGenerator("1234567890",4);
        captcha.setGenerator(randomGenerator);
        captcha.createCode();
        String code = captcha.getCode();

        cacheService.setCacheObject(VerificationCodeConstant.GET_IMAGE_CODE, code, 1L, TimeUnit.DAYS);

        try {
            captcha.write(response.getOutputStream());
        } catch (IOException e) {
            log.error("输出验证码失败", e);
        }
    }


    /**
     * 检查图形验证码
     * @param code
     * @return
     */
    public boolean checkCode(String code) {
        String cacheCode = cacheService.getCacheObject(VerificationCodeConstant.GET_IMAGE_CODE);
        if (!StrUtil.equalsIgnoreCase(code, cacheCode)) {
            throw new ServiceException(LoginCode.CodeError);
        }

        cacheService.deleteObject(VerificationCodeConstant.GET_IMAGE_CODE);

        return true;
    }

}
